package Recursion;

/**
 * Created with IntelliJ IDEA.
 * User: Bjarke
 * Date: 06-11-13
 * Time: 22:22
 * To change this template use File | Settings | File Templates.
 */
public class Recursion {

    /**
     * Formular for triangular numbers:
     * number + sum(previous numbers) while numbers > 0
     * @param number
     * @return
     */

    public int getTriangularNum(int number){
        int triangularNumber = 0;


        // Triangular number for 3:
        // 3 + 2 + 1

        while (number > 0){
            triangularNumber = triangularNumber + number;
            number--;
        }
        return triangularNumber;
    }

    public int getTriangularNumberR(int number){
        System.out.println("Method " + number);

        // base case
        if (number == 1){

            System.out.println("Returned 1");
            return 1;
        } else{
            int result = number + getTriangularNumberR(number - 1);

            System.out.print("Returned " + result);
            System.out.println(" : " + number + " getTN( " + number + " - 1 )");

            return result;
        }
    }


    /**
     * Factorial: F(n) = n * n-1 * n-2 * n-3 ... while n > 0
     */
    // F(3) = 3 * 2 * 1

    public int getFactorialR(int number){
        System.out.println("Method " + number);

        if (number == 1){

            System.out.println("Returned 1");
            return 1;
        } else {
            int result = number * getFactorialR(number - 1);

            System.out.print("Returned " + result);
            System.out.println(" : " + number + " * getFac( " + number + " - 1 )");
            return result;
        }
    }

    public static void main(String args[]){

        Recursion recursionTool = new Recursion();

        //System.out.println(recursionTool.getTriangularNum(6));

        //System.out.println(recursionTool.getTriangularNumberR(6));

        System.out.println(recursionTool.getFactorialR(6));
    }
}
